package io.noties.markwon.plugin.highlight.span

import android.graphics.Color
import android.text.TextPaint
import android.text.style.MetricAffectingSpan
import androidx.annotation.ColorInt
import com.gitee.wsl.android.ext.base.getContrastRatio
import com.gitee.wsl.android.ext.base.isDarkColor
import com.gitee.wsl.ext.base.ColorExt

import io.noties.markwon.theme.MarkwonTheme

class HighlightSpan(
    theme: MarkwonTheme,
    @field:ColorInt @param:ColorInt private val mainColor: Int=theme.colorSchemeAndroid.onPrimaryContainer,
    @field:ColorInt @param:ColorInt private val highlightColor: Int=theme.colorSchemeAndroid.textColorHighlight,
    private val current: Boolean = true,
    private val darkTheme: Boolean = false
) : MetricAffectingSpan() {
    override fun updateDrawState(tp: TextPaint) {
        if (current) {
            if (darkTheme) {
                if (ColorExt.isDarkColor(mainColor)) {
                    tp.bgColor = Color.WHITE
                    tp.color = mainColor
                } else {
                    tp.bgColor = mainColor
                    tp.color = Color.BLACK
                }
            } else {
                if (ColorExt.isDarkColor(mainColor)) {
                    tp.bgColor = mainColor
                    tp.color = Color.WHITE
                } else {
                    if (ColorExt.getContrastRatio(mainColor, highlightColor) > 3.0) {
                        tp.bgColor = highlightColor
                    } else {
                        tp.bgColor = Color.BLACK
                    }
                    tp.color = mainColor
                }
            }
        } else {
            tp.bgColor = highlightColor
            if (ColorExt.getContrastRatio(mainColor, highlightColor) > 3.0) {
                tp.color = mainColor
            } else {
                if (darkTheme) {
                    tp.color = Color.WHITE
                } else {
                    tp.color = Color.BLACK
                }
            }
        }
        tp.isFakeBoldText = true
    }

    override fun updateMeasureState(tp: TextPaint) {
        tp.isFakeBoldText = true
    }
}